import 'dart:async';
import 'dart:convert';
import 'package:convert/convert.dart';

import 'package:app_review/app_review.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reader/dao/book_collect_data_manager.dart';
import 'package:flutter_reader/dao/main_data_manager.dart';
import 'package:flutter_reader/navigator/tab_navigator.dart';
import 'package:flutter_reader/new/config_provider.dart';
import 'package:flutter_reader/new/provider_setup.dart';
import 'package:flutter_reader/pages/me/vip_page.dart';
import 'package:flutter_reader/pages/read_book/book_catelog.dart';
import 'package:flutter_reader/tools/global_state.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:intro_views_flutter/Models/page_view_model.dart';
import 'package:intro_views_flutter/intro_views_flutter.dart';
import 'package:notification_permissions/notification_permissions.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:crypto/crypto.dart' as crypto;
import 'package:flutter_reader/tools/globals.dart' as globals;
import 'dart:io' show Platform;


void main() {
  final hasLogin = GlobalModel();

  runApp(
    Provider<bool>.value(
    child: ChangeNotifierProvider.value(value: hasLogin,
    child: MyApp(),),
    )
  );
}


class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: providers,
      child: Consumer<ConfigProvider>(
        builder: (BuildContext context, ConfigProvider appInfo, Widget child){
          return OverlaySupport(
            child: MaterialApp(
              title: '爱看',
              debugShowCheckedModeBanner: false,
              theme: ThemeData(
                  primarySwatch: Colors.red,
                  accentColor: Color(0xffe53935),
                  buttonTheme: ButtonThemeData(
                    buttonColor: Color(0xffe53935),
                    shape: RoundedRectangleBorder(),
                  )
              ),
              home: Splash(),
            ),
          );
        },
      ),
    );
  }
}

class Splash extends StatefulWidget {
  @override
  SplashState createState() => new SplashState();
}

class SplashState extends State<Splash> {


  final pages =
  [
    PageViewModel(
        pageColor: Colors.lightBlueAccent,
        body: Container(
          height: 250,
          child: Text(
            '海量小说尽情阅读 书籍海洋',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 18),
          ),
      ),
        title: Container(
          margin: EdgeInsets.only(top: 30),
          child: Text(
            '应有尽有',
            style: TextStyle(fontSize: 25),
          ),
        ),
        mainImage: Image.asset(
          'images/fl_intro2.png',
          height: 100.0,
          width: 200.0,
          fit: BoxFit.contain,
          alignment: Alignment.center,
        )),
//    PageViewModel(
//        pageColor: Colors.lightGreen,
//        body: Container(
//          height: 250,
//          child: Text(
//            '界面丰富 功能多样 私人书城',
//            textAlign: TextAlign.center,
//            style: TextStyle(fontSize: 18),
//          ),
//        ),
//        title: Container(
//          margin: EdgeInsets.only(top: 30),
//          child: Text(
//            '前所未有',
//            style: TextStyle(fontSize: 25),
//          ),
//        ),
//        mainImage: Image.asset(
//          'images/fl_intro3.png',
//          height: 150.0,
//          width: 250.0,
//          fit: BoxFit.contain,
//          alignment: Alignment.center,
//        )),
//    PageViewModel(
//        pageColor: Colors.redAccent,
//        body: Container(
//          height: 250,
//          child: Text(
//            '开启你的小说之旅 体验阅读',
//            textAlign: TextAlign.center,
//            style: TextStyle(fontSize: 18),
//          ),
//        ),
//        title: Container(
//          margin: EdgeInsets.only(top: 30),
//          child: Text(
//            '立即体验',
//            style: TextStyle(fontSize: 25),
//          ),
//        ),
//        mainImage: Image.asset(
//          'images/fl_intro1.png',
//          height: 150.0,
//          width: 250.0,
//          fit: BoxFit.contain,
//          alignment: Alignment.center,
//        )),
  ];

  Future checkFirstSeen() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool _seen = (prefs.getBool('seen') ?? false);
    bool localNeedBook = prefs.get("needAddBook") ?? false;
    if (_seen) {
      print("--------------- 不是第一次启动 --------------");
      globals.isFirst = false;
      if(localNeedBook == true)
        {
          globals.needAddBook = true;
        }
      else
        {
          globals.needAddBook = false;
        }
      judgeGoOther();
      Navigator.of(context).pushReplacement(
          new MaterialPageRoute(builder: (context) => new TabNavigator()));
    } else {
      print("--------------  第一次启动 --------------");
      globals.isFirst = true;
      globals.needAddBook = true;
      judgeDialog();
      judgeGoOther();
      prefs.setBool('seen', true);
      Navigator.of(context).pushReplacement(
          new MaterialPageRoute(builder: (context) => Builder(
            builder: (context) => IntroViewsFlutter(
              pages,
//              skipText: Text('跳过'),
              doneText: Text('开始'),
              pageButtonsColor: Colors.white,
              onTapDoneButton: () {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder: (context) => TabNavigator(),
                  ), //MaterialPageRoute
                );
              },
            ), //IntroViewsFlutter
          )));
    }
  }


  ///弹窗控制 开启：3  关闭：0
  judgeDialog() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setInt("dialog", 3);
  }

  ///跳转到其他页面 返回后不进行弹窗
  judgeGoOther() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setBool("goOther", false);
  }

  String _udid = 'Unknown';
  int localDate;


  @override
  void dispose() {
    super.dispose();
  }

  Future<void> getUdid() async {
    String udid;
    try {
      udid = await FlutterUdid.udid;
    } on
    PlatformException {
      udid = 'Failed to get UDID.';
    }
    _udid = udid;
    print('udid:${_udid}');
    globals.uuid = _udid;
    String MapCode = 'request_date' + localDate.toString() + 'uuid' + _udid + globals.appKey;
    print('Map:${MapCode}');
    String autographCode = generateMd5(MapCode);
    print('MD5:${autographCode}');
    globals.autographCode = autographCode;
    MainDao.getSessionID(autographCode, localDate, _udid).then((value){
      print('sessionID:${value['data']['SessionID']}');
      globals.fullSessionID = value['data']['SessionID'];
    });
  }

  needLogin() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String localSessionID = prefs.getString('fullSessionID');
    if(localSessionID == null){
      MainDao.fetchDateTime().then((value){
        print('未登录用户');
        print('---------获取游客账号--------');
        print(value['data']['datetime']);
        int dateTime = value['data']['datetime'];
        print('severDate:${dateTime}');
        print('localDate:${DateTime.now().millisecondsSinceEpoch}');
        localDate = ((DateTime.now().millisecondsSinceEpoch)~/1000).toInt();
        ///本地和服务器时间差    本地时间 - 服务器时间
        int dateError = localDate - dateTime;
        print('dateError:${dateError}');
        globals.dateError = dateError;
        getUdid();
      });
    }
    else
      {
        print('已登录用户');
        print('--------是否需要重新登录----------');
        globals.fullSessionID = localSessionID;
        String preLoginDate = prefs.getString('LoginDate');
        DateTime lastLogin = DateTime.parse(preLoginDate);
        print('上一次登录时间：${lastLogin}');
        DateTime now = DateTime.now();
        final different = now.difference(lastLogin).inDays;
        print('距离上次登录已经${different.toString()}天');
        if(different >= 30){
          print('登录过期，转为游客账号');
          prefs.setString('login', 'false');
          prefs.setString('fullSessionID', null);
          MainDao.fetchDateTime().then((value){
            print('未登录用户');
            print('---------获取游客账号--------');
            print(value['data']['datetime']);
            int dateTime = value['data']['datetime'];
            print('severDate:${dateTime}');
            print('localDate:${DateTime.now().millisecondsSinceEpoch}');
            localDate = ((DateTime.now().millisecondsSinceEpoch)~/1000).toInt();
            ///本地和服务器时间差    本地时间 - 服务器时间
            int dateError = localDate - dateTime;
            print('dateError:${dateError}');
            globals.dateError = dateError;
            getUdid();
          });
        }
        else
          {
            print('登录未过期，保持登录状态');
            MainDao.fetchDateTime().then((value){
              print(value['data']['datetime']);
              int dateTime = value['data']['datetime'];
              print('severDate:${dateTime}');
              print('localDate:${DateTime.now().millisecondsSinceEpoch}');
              localDate = ((DateTime.now().millisecondsSinceEpoch)~/1000).toInt();
              ///本地和服务器时间差    本地时间 - 服务器时间
              int dateError = localDate - dateTime;
              print('dateError:${dateError}');
              globals.dateError = dateError;
            });
          }
      }
  }

  generateMd5(String data) {
    var content = new Utf8Encoder().convert(data);
    var md5 = crypto.md5;
    var digest = md5.convert(content);
    return hex.encode(digest.bytes);
  }

  @override
  void initState() {
    initUmeng();
    checkFirstSeen();
    needLogin();
    getVersion();
    super.initState();
  }

  getVersion() async{
    //获取当前版本
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
  }
  String _result;



//  initUMeng() {
//    if(Platform.isAndroid){
//      FlutterUmplus.init(
//        '5df720f40cafb28f17000701',
//        channel: "v1.0",
//        reportCrash: true,
//        logEnable: true,
//        encrypt: true,
//      );
//    }else if(Platform.isIOS){
//      //iOS平台
//      FlutterUmplus.init(
//        '5df73ab2570df30c90000ec9',
//        channel: null,
//        reportCrash: false,
//        logEnable: true,
//        encrypt: true,
//      );
//    }
//  }

  static Future<void> initUmeng() async{
    // LcfarmFlutterUmeng.init(
    //     iOSAppKey: "5df73ab2570df30c90000ec9",
    //     androidAppKey: "5df720f40cafb28f17000701",
    //     logEnable: true,
    //     encrypt: false,
    //     channel: 'v1.0.1'
    // );
  }


  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Text('正在载入...'),
      ),
    );
  }
}

